import datetime
import hashlib
import os
import time
from urllib import parse

import requests
from bs4 import BeautifulSoup


class HtmlParse:
    def __init__(self, content):
        self.wximg_disk = {}
        self.img_count = 0
        self.cur_time = datetime.datetime.now().strftime('%Y%m')
        self.path = self.gene_folder(self.cur_time)
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36',
        }
        self.parse_html(content)

    def get_dict(self):
        return self.wximg_disk

    def parse_html(self, content):
        print('解析中请稍后...')
        soup = BeautifulSoup(content, 'lxml')
        all_img = soup.find_all('img')
        img_count = len(all_img)
        print('开始下载图片')

        for img in all_img:
            url = img.get('src')
            if url.startswith('https://mmbiz.qpic.cn'):
                r = requests.get(url, headers=self.headers)
                # img_name = self.gene_name(url, index)
                img_name = self.gene_name2(url, r.content)
                img_path = os.path.join(self.path, img_name)
                self.wximg_disk[url] = img_path
                with open(img_path, 'wb') as f:
                    f.write(r.content)
                time.sleep(0.5)
                self.img_count += 1
                print('正在下载第 %d 个...' % self.img_count)

        print('下载图片完成。共 %d 个' % self.img_count)

    def gene_name(self, url, index):
        result = parse.urlparse(url)
        query_dict = parse.parse_qs(result.query)
        ext = query_dict['wx_fmt'][0]
        name = datetime.datetime.now().strftime('%d-%H-%M-%S') + "-" + str(index) + '.' + ext
        return name

    def gene_name2(self, url, content):
        result = parse.urlparse(url)
        query_dict = parse.parse_qs(result.query)
        ext = query_dict['wx_fmt'][0]
        m = hashlib.md5()
        m.update(content)
        return datetime.datetime.now().strftime('%d') + "-" + m.hexdigest() + '.' + ext

    def gene_folder(self, cur_time):
        path = os.path.join(os.path.dirname(__file__), cur_time)
        if not os.path.exists(path):
            os.makedirs(path)
        return path


if __name__ == '__main__':
    path = 'test1.html'
    parse = HtmlParse(path)
    dict = parse.get_dict()
